package com.foeye.ws.utils;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class XmlUtil {
	
	/**
	 * object to strxml
	 * 
	 * @param obj
	 * @return
	 * @author yanjr
	 */
	public static String objToXml(Object obj) {
		try {
			JAXBContext content = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = content.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");//编码格式
//			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串
//			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);// 是否省略xml头声明信息
			
			ByteArrayOutputStream os = new ByteArrayOutputStream();
//			StringWriter writer = new StringWriter();
			
			marshaller.marshal(obj, os);
			return new String(os.toByteArray());
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * strxml to Object
	 * 
	 * @param strXml
	 * @param classType
	 * @return
	 * @author yanjr
	 */
	public static <T> T xmlToObject(String strXml, Class<T> classType) {
		try {
			JAXBContext content = JAXBContext.newInstance(classType);
			Unmarshaller unmarshaller = content.createUnmarshaller();
			@SuppressWarnings("unchecked")
			T bean = (T) unmarshaller.unmarshal(new StringReader(strXml));
			return bean;
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	
	public static void main(String[] args) {
		/*
		TestUser user = new TestUser();
		user.setId("1");
		user.setName("Tom");
		user.setAge(12);
		String strUser = XmlUtil.objToXml(user);
		System.out.println(strUser);
		*/
		
		
		
		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><testUser><age>12</age><id>1</id><name>Tom</name></testUser>";
		TestUser user = XmlUtil.xmlToObject(xml, TestUser.class);
		System.out.println(user.getId() + "\n" + user.getName() + "\n" + user.getAge());
		
		
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	

}
